<script setup lang="ts">
import { ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import KnowledgePicker from '@/components/view/KnowledgePicker.vue'
import FormDocument from '@/components/form/FormDocument.vue'
import { documentDelete, documentList, documentSave } from '@/api/interface/web/doc'
import { fileDelete, fileDownload, fileUpload } from '@/api/interface/common/file'
import { numCeilToFixed1 } from '@/utils/common'
// import { fileUpload } from '@/api/interface/common/file'

const fullscreenLoading = ref(false)

const knowledgeRef = ref()

const searchForm = ref<any>({
  rangeDate: [],
})

const knowledgeId = ref<string>('')

const baseTableRef = ref()

const conditionMethod = () => {
  const cond: any = {}
  Object.keys(searchForm.value).map((key) => {
    if (searchForm.value[key] || searchForm.value[key] === 0) {
      if (key === 'rangeDate') {
        if (searchForm.value[key]) {
          cond['createTime'] = searchForm.value[key][0]
          cond['updateTime'] = searchForm.value[key][1]
        }
      } else {
        cond[key] = searchForm.value[key]
      }
    }
  })

  cond['knowledgeId'] = knowledgeId.value
  return cond
}

const handleSearch = () => {
  baseTableRef.value.refresh()
}

const handleResetSearch = () => {
  searchForm.value = {
    rangeDate: [],
  }
  baseTableRef.value.refresh()
}

const changeKnowledge = (data: any) => {
  knowledgeId.value = data
  baseTableRef.value.refresh()
}

// 删除
const handleDelete = (row: any) => {
  const { id, fileName } = row
  ElMessageBox.confirm('确定删除文档?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    autofocus: false,
  }).then(() => {
    fullscreenLoading.value = true
    fileDelete({ fileName })
      .then(() => {
        documentDelete({ id })
          .then(() => {
            ElMessage({
              message: '删除成功!',
              type: 'success',
            })

            baseTableRef.value.refreshStay()
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      })
      .catch(() => {
        fullscreenLoading.value = false
      })
  })
}

// 添加编辑
const dialogVisible = ref(false)

const addEditData = ref<any>({})

const addEditStatus = ref('add')

const formUserRef = ref()

const handleAdd = () => {
  addEditStatus.value = 'add'
  addEditData.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  addEditStatus.value = 'edit'
  addEditData.value = row
  dialogVisible.value = true
}

const handleDialogClose = () => {
  dialogVisible.value = false
}

// 允许上传的文件格式
const allowed = [
  '.txt',
  '.md',
  '.json',
  '.doc',
  '.docx',
  '.xls',
  '.xlsx',
  '.ppt',
  '.pptx',
  '.pdf',
  '.csv',
  '.html',
  '.htm',
]
//校验文件格式
const isExtensionAllowed = (item: any) => {
  // 找到最后一个点的位置
  const lastDotIndex = item.name.lastIndexOf('.')
  // 如果没有点，或者点在最后一位（没有扩展名），返回 false
  if (lastDotIndex === -1 || lastDotIndex === item.name.length - 1) {
    return false
  }
  // 提取扩展名（包含点）
  const ext = item.name.slice(lastDotIndex).toLowerCase() // 转小写，避免大小写问题
  // 判断是否在允许列表中
  return {
    isAllowed: allowed.includes(ext),
    format: ext,
  }
}

const handleDialogSubmit = () => {
  formUserRef.value.submitForm().then((data: any) => {
    if (data) {
      fullscreenLoading.value = true
      const { id, name, knowledgeId, fileList } = data

      // 文件上传相关处理
      const newImgs = fileList.filter((item: any) => !item.url || item.url.indexOf('blob:') === -1)

      // 判断格式
      const notAllowedFiles: any = []
      newImgs.forEach((item: any) => {
        const isExtensionAllowedRes: any = isExtensionAllowed(item)
        if (!isExtensionAllowedRes.isAllowed) {
          notAllowedFiles.push(item)
        }
        item.format = isExtensionAllowedRes.format
      })
      if (notAllowedFiles.length) {
        notAllowedFiles.forEach((item: any) => {
          ElMessage.error(`文件《${item.name}》格式不正确，请重新选择文件！`)
        })
        return
      }

      // 判断大小
      const illegalFiles: any = []
      newImgs.forEach((item: any) => {
        const size = item.raw.size / 1024
        if (size > 500) {
          illegalFiles.push(item)
        }

        if (size < 1024) {
          item.size = numCeilToFixed1(size) + 'KB'
        } else {
          item.size = numCeilToFixed1(size) + 'MB'
        }
      })

      if (illegalFiles?.length) {
        illegalFiles.forEach((item: any) => {
          ElMessage.error(`文件《${item.name}》超过500M，请重新选择文件！`)
        })
        return
      }

      if (newImgs.length && newImgs[0]) {
        const { raw, format, size } = newImgs[0]
        fileUpload(raw).then((res: any) => {
          documentSave({
            id,
            name,
            knowledgeId,
            format: format,
            fileSize: size,
            fileUrl: res.fileUrl,
            fileName: res.fileName,
          })
            .then(() => {
              ElMessage({
                message: '操作成功!',
                type: 'success',
              })
              dialogVisible.value = false

              if (addEditStatus.value == 'add') {
                baseTableRef.value.refresh()
              } else if (addEditStatus.value == 'edit') {
                baseTableRef.value.refreshStay()
              }
            })
            .finally(() => {
              fullscreenLoading.value = false
            })
        })
      } else {
        ElMessage({
          message: '请选择文件!',
          type: 'error',
        })
        fullscreenLoading.value = false
      }
    }
  })
}

// 下载
const handleDownload = (row: any) => {
  // const a = document.createElement('a')
  // a.href = row.fileUrl
  // // 处理中文文件名
  // a.download = row.name
  // document.body.appendChild(a)
  // a.click()
  // document.body.removeChild(a)
  fileDownload({ fileName: row.fileName }).then((res: any) => {
    console.log(res)
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob) // 创建 url 并指向 blob
    const a = document.createElement('a')
    a.href = url
    a.download = row.name
    a.click()
    window.URL.revokeObjectURL(url)
  })
}
</script>

<template>
  <BasePageWrapper v-loading.fullscreen="fullscreenLoading">
    <BasePage>
      <template #title>文档管理</template>
      <template #toolbar>
        <el-button type="primary" @click="handleAdd">
          <template #icon>
            <el-icon><Plus /></el-icon>
          </template>
          新增
        </el-button>
      </template>
      <template #searchbar>
        <el-form :inline="true" :model="searchForm" @submit.prevent>
          <el-form-item label="文档名称：">
            <el-input v-model="searchForm.name" placeholder="请输入文档名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="info" text bg @click="handleResetSearch">
              <template #icon>
                <el-icon><Refresh /></el-icon>
              </template>
              重置
            </el-button>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><Search /></el-icon>
              </template>
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </template>
      <div class="page-content-container">
        <div class="left">
          <KnowledgePicker ref="knowledgeRef" @change="changeKnowledge"></KnowledgePicker>
        </div>
        <div class="right">
          <BaseTable
            ref="baseTableRef"
            :init-table-method="documentList"
            :condition-method="conditionMethod"
          >
            <el-table-column
              type="index"
              label="编号"
              align="center"
              header-align="center"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="文档名称"
              min-width="100"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="format"
              label="格式"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="fileSize"
              label="文件大小"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button type="primary" link @click="handleDownload(scope.row)">下载</el-button>
                <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </BaseTable>
        </div>
      </div>
    </BasePage>
  </BasePageWrapper>
  <BaseDialog v-model="dialogVisible" width="35%">
    <template #title>{{ addEditStatus === 'add' ? '新增' : '编辑' }}</template>
    <template #buttons>
      <el-button type="info" text bg @click="handleDialogClose">取消</el-button>
      <el-button type="primary" @click="handleDialogSubmit">保存</el-button>
    </template>
    <FormDocument ref="formUserRef" :data="addEditData" :status="addEditStatus"></FormDocument>
  </BaseDialog>
</template>

<style lang="scss" scoped>
.page-content-container {
  @include rect(100%, 100%);
  @include flex(row, space-between, flex-start);
  .left {
    @include rect(220px, 100%);
    box-sizing: border-box;
    padding-bottom: 24px;
  }
  .right {
    @include rect(calc(100% - 240px), 100%);
    :deep(.role-tag) {
      margin-right: 10px;
      margin-top: 5px;
      margin-bottom: 5px;
    }
    .icon-text-box {
      display: flex;
      justify-content: center;
      align-items: center;

      .icon-text {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 24px;
        cursor: pointer;
        .icon {
          margin-right: 5px;
          font-size: 16px;
        }
        .text {
          width: 2em;
        }
        .text.add {
          min-width: 4em;
        }
      }
      .icon-text:last-child {
        margin-right: 0;
      }
      .icon-text.info {
        color: var(--theme-color);
      }
      .icon-text.delete {
        color: #f56c6c;
      }
    }
  }
}
</style>
